package com.yxy.chatserver.handler;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.yxy.chatserver.constant.FriendRequestStatusConstant;
import com.yxy.chatserver.constant.MessageStatusConstant;
import com.yxy.chatserver.constant.MessageTypeConstant;
import com.yxy.chatserver.domain.po.FriendMessage;
import com.yxy.chatserver.domain.po.FriendRequest;
import com.yxy.chatserver.domain.po.Friends;
import com.yxy.chatserver.domain.vo.FriendRequestVO;
import com.yxy.chatserver.domain.po.User;
import com.yxy.chatserver.mapper.UserMapper;
import com.yxy.chatserver.service.FriendRequestService;
import com.yxy.chatserver.service.MessageService;
import com.yxy.chatserver.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.time.LocalDateTime;

/**
 * 处理好友请求
 */
@Component
@Slf4j
public class FriendRequestHandler {
    @Autowired
    private WebSocketManager webSocketManager;
    @Autowired
    private FriendRequestService friendRequestService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private Gson gson;

    /**
     * 处理好友请求
     * @param session
     * @param jsonObject
     * @param fromUserId
     */
    public void handleMessage(WebSocketSession session, JsonObject jsonObject, String fromUserId) throws Exception {
        String type = jsonObject.get("type").getAsString();
        switch (type) {
            case "friendRequest":
                // 添加好友请求
                handleSendFriendRequest(session, jsonObject, fromUserId);
                break;
            case "acceptRequest":
            case "rejectRequest":
                // 接受好友请求（考虑合并处理好友请求的响应）
                handleAcceptFriendRequest(session, jsonObject, fromUserId);
                break;
            default:
                break;
        }
    }

    /**
     * 处理接受好友请求
     * @param session
     * @param jsonObject
     * @param fromUserId
     */
    private void handleAcceptFriendRequest(WebSocketSession session, JsonObject jsonObject, String fromUserId) throws Exception {
        String toUserId = jsonObject.get("toUserId").getAsString();
        fromUserId = jsonObject.get("fromUserId").getAsString();
        String fromUserNickname = jsonObject.get("fromUserNickname").getAsString();
        String fromUserAvatar = jsonObject.get("fromUserAvatar").getAsString();
        String toUserNickname = jsonObject.get("toUserNickname").getAsString();
        String toUserAvatar = jsonObject.get("toUserAvatar").getAsString();
        String status = jsonObject.get("status").getAsString();
        LocalDateTime sendTime = LocalDateTime.parse(jsonObject.get("timestamp").getAsString());
        if(status.equals(FriendRequestStatusConstant.ACCEPTED)){
            // 判断好友是否存在
            Boolean isExists = userService.checkFriend(fromUserId, toUserId);
            if(isExists){
                // 如果已存在，则返回错误信息
                sendAck(session, MessageTypeConstant.FRIEND_EXISTS, "好友已存在");
                return;
            }
            // 更新状态
            friendRequestService.updateFriendRequest(fromUserId, toUserId, status, sendTime);
            // 在好友表中新增好友信息
            userService.addFriend(fromUserId, toUserId, toUserNickname, toUserAvatar);
            userService.addFriend(toUserId, fromUserId, fromUserNickname, fromUserAvatar);
            JsonObject data = new JsonObject();
            data.addProperty("message", "accepted");
            data.addProperty("id", Long.parseLong(jsonObject.get("id").getAsString()));
            JsonObject response = new JsonObject();
            response.add("data", data);
            sendAck(session, MessageTypeConstant.FRIEND_ACCEPT, gson.toJson(response));
        }else if(status.equals(FriendRequestStatusConstant.REJECTED)){
            friendRequestService.updateFriendRequest(fromUserId, toUserId, status, sendTime);
            JsonObject data = new JsonObject();
            data.addProperty("message", "rejected");
            data.addProperty("id", Long.parseLong(jsonObject.get("id").getAsString()));
            JsonObject response = new JsonObject();
            response.add("data", data);
            sendAck(session, MessageTypeConstant.FRIEND_REJECTED, gson.toJson(response));
        }
    }

    /**
     * 处理发送好友请求
     * @param session
     * @param jsonObject
     * @param fromUserId
     */
    private void handleSendFriendRequest(WebSocketSession session, JsonObject jsonObject, String fromUserId) throws Exception {
        String toUserId = jsonObject.get("toUserId").getAsString();
        String note = jsonObject.get("content").getAsString();
        LocalDateTime sendTime = LocalDateTime.parse(jsonObject.get("timestamp").getAsString());
        // 创建好友请求（持久化到数据库）
        FriendRequest friendRequest = friendRequestService.createFriendRequest(fromUserId, toUserId, note, sendTime);
        FriendRequestVO friendRequestVO = new FriendRequestVO();
        BeanUtils.copyProperties(friendRequest, friendRequestVO);
        // 获取接收方和发送方的部分信息进行缓存
        User fromUser = userService.getById(fromUserId);
        User toUser = userService.getById(toUserId);
        // 获取接收者会话
        WebSocketSession toSession = webSocketManager.getSessionByUserId(toUserId);
        if(toSession != null && toSession.isOpen()){
            // 如果接收者在线，直接推送
            log.info("用户 {} 在线，已推送好友申请", toUserId);
            friendRequestVO.setId(friendRequest.getId());
            friendRequestVO.setFromUserNickname(fromUser.getNickname());
            friendRequestVO.setFromUserAvatar(fromUser.getAvatar());
            friendRequestVO.setToUserNickname(toUser.getNickname());
            friendRequestVO.setToUserAvatar(toUser.getAvatar());
            sendFriendRequest(toSession, friendRequestVO);
        }else{
            // 如果不在线，则保存请求，等待接收者上线时推送
            log.info("用户 {} 不在线，已保存好友申请", toUserId);
            FriendMessage friendMessage = new FriendMessage();
            friendMessage.setFriendId(friendRequest.getId());
            friendMessage.setFromUserId(fromUserId);
            friendMessage.setToUserId(toUserId);
            friendMessage.setType(MessageTypeConstant.NEW_FRIEND_REQUEST);
            friendMessage.setSendTime(sendTime);
            friendMessage.setStatus(MessageStatusConstant.SENT);
            friendMessage.setNote(note);
            friendMessage.setRequestStatus(FriendRequestStatusConstant.PENDING);
            messageService.saveMessage(friendMessage);
        }
        // 发送确认回执给发起方
        sendAck(session, MessageTypeConstant.FRIEND_REQUEST_SUCCESS, "请求已发送");
    }
    /**
     * 发送好友请求给目标用户
     */
    private void sendFriendRequest(WebSocketSession session, FriendRequestVO request) throws Exception {
        JsonObject message = new JsonObject();
        message.addProperty("type", MessageTypeConstant.NEW_FRIEND_REQUEST);
        message.add("data", gson.toJsonTree(request));
        session.sendMessage(new TextMessage(message.toString()));
    }

    /**
     * 发送确认回执
     */
    private void sendAck(WebSocketSession session, String ackType, String content) throws Exception {
        JsonObject ack = new JsonObject();
        ack.addProperty("type", ackType);
        ack.addProperty("content", content);
        session.sendMessage(new TextMessage(ack.toString()));
    }
}
